<?php
namespace app\logic;




use app\models\Cart;
use app\models\Channel;
use app\models\GoodsSku;
use app\models\Order;
use app\models\OrderGoods;
use Yii;

class CartLogic
{

    public function getCart($user_id){
        $cart = Cart::find()->where(['user_id'=>(int)$user_id]);
        $skus = $cart->asArray()->all();
        $sku_ids = array_column($skus,'sku_id');
        $goodsSku = GoodsSku::find()
            ->select('gs.*,g.status,g.buy_status')
            ->from('{{%goods_sku}} gs')
            ->leftJoin('{{%goods}} g','g.goods_id=gs.goods_id')
            ->where(['gs.sku_id'=>$sku_ids])
            ->asArray()->all();
        $sku_status = [];
        foreach($goodsSku AS &$item){
            $sku_status[$item['sku_id']] = $item['status'];
        }
        foreach($skus AS $key=>&$value){
            foreach($goodsSku AS $v){
                if($value['sku_id'] == $v['sku_id']){
                    /*$value['inventory'] = $v['inventory'];
                    $value['inventory_status'] = $v['inventory_status'];*/
                    if($v['inventory']==0 || $v['inventory_status']==0 || $v['status']==0 || $v['buy_status']==0 || $value['num']>$v['inventory'])
                        $value['status'] = 0;
                    else
                        $value['status'] = 1;
                }
            }
        }

        $num = $cart->sum('num');
        if(!$num)
            $num = 0;
        $total_amount = $cart->sum('sku_amount');
        if(!$total_amount)
            $total_amount = 0.00;
        return ['skus'=>$skus,'total_num'=>$num,'total_amount'=>$total_amount/*,'sku_status'=>$sku_status*/];
    }

    public function addCart($user_id,$sku_id,$num){
        $goodsSku = GoodsSku::find()
            ->select('gs.*,g.goods_name')
            ->from('{{%goods_sku}} gs')
            ->leftJoin('{{%goods}} g','g.goods_id=gs.goods_id')
            ->where(['gs.sku_id'=>$sku_id])
            ->asArray()->one();
        $sku_spec = [];
        $sku_spec_temp = json_decode($goodsSku['sku_spec'],true);
        foreach ($sku_spec_temp AS $key=>$value){
            $sku_spec[] = $value['spec_value'];
        }
        $sku_spec = json_encode($sku_spec);
        if($cart = Cart::findOne(['user_id'=>(int)$user_id,'sku_id'=>(int)$sku_id])){
            $cart->num += (int)$num;
            $cart->sku_amount = (double)($cart->sku_price*$cart->num);
            return $cart->save();
        }else{
            $cart = new Cart();
            $cart->user_id = (int)$user_id;
            $cart->goods_id = (int)$goodsSku['goods_id'];
            $cart->sku_id = (int)$sku_id;
            $cart->yx_sku_id = (string)$goodsSku['yx_sku_id'];
            $cart->sku_pic = (string)$goodsSku['sku_pic'];
            $cart->goods_name = (string)$goodsSku['goods_name'];
            $cart->sku_spec = (string)$sku_spec;
            $cart->sku_price = (double)$goodsSku['sku_price'];
            $cart->num = (int)$num;
            $cart->sku_amount = (double)($goodsSku['sku_price']*$num);
            return $cart->save();
        }

    }

    public function editCart($user_id,$sku_id,$num){
        $cart = Cart::findOne(['user_id'=>(int)$user_id,'sku_id'=>(int)$sku_id]);
        $cart->num = (int)$num;
        $cart->sku_amount = (double)($cart->sku_price*$num);
        return $cart->save();
    }

    public function delCart($user_id,$sku_id){
        $cart = Cart::findOne(['user_id'=>(int)$user_id,'sku_id'=>(int)$sku_id]);
        return $cart->delete();
    }

    public function getGoodsSkuAmount($sku_ids,&$skus,&$goods_amount,&$channel_amount,&$goods_name,&$allon,&$stock_status,&$no_goods_name){
        $goodssku =  GoodsSku::find()
            ->select('gs.*,g.status,g.buy_status,g.goods_name,g.yx_goods_id')
            ->from('{{%goods_sku}} gs')
            ->leftJoin('{{%goods}} g','g.goods_id=gs.goods_id')
            ->where(['gs.sku_id'=>$sku_ids])->asArray()->all();
        $no_goods_name = '';
        $goods_amount = 0;
        $channel_amount = 0;
        $allon = true;
        $stock_status = true;
        foreach($goodssku AS $key=>$value){
            if($value['inventory']==0 || $value['inventory_status']==0){
                $stock_status &= false;
                if(!$no_goods_name)
                    $no_goods_name .= $value['goods_name'];
                else
                    $no_goods_name .= '、'.$value['goods_name'];
            }
            if($value['status']==0 || $value['buy_status']==0){
                $allon &= false;
            }
            foreach ($skus AS $k=>&$v){
                if($k==0){
                    $goods_name = $v['goods_name'];
                }
                if($value['sku_id'] == $v['sku_id']){
                    $com_sku_spec = [];
                    $v['yx_goods_id'] = $value['yx_goods_id'];
                    $v['goods_id'] = $value['goods_id'];
                    $v['yx_sku_id'] = $value['yx_sku_id'];
                    $v['channel_price'] = $value['channel_price'];
                    $sku_spec = json_decode($value['sku_spec'],true);
                    foreach($sku_spec AS $kk=>$vv){
                        $com_sku_spec[] = $vv['spec_value'];
                    }
                    sort($com_sku_spec);
                    sort($v['sku_spec']);
                    if(json_encode($v['sku_spec'])!=json_encode($com_sku_spec)){
                        return false;
                    }elseif((float)$value['sku_price']!=(float)$v['sku_price']){
                        return false;
                    }else{
                        $goods_amount += $value['sku_price']*$v['num'];
                        $channel_amount += $value['channel_price']*$v['num'];
                    }
                }
            }
        }
        return true;
    }

    public function submitOrder($user_id,$name,$phone,$province,$city,$district,$address,$skus,$goods_amount,$channel_amount,$channel_code=null,&$order_no,&$order_time,&$order_amount,$is_buynow=1){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $order = new Order();
        $order_no = $this->createOrderNo();
        $order3 = Order::findOne(['order_no'=>$order_no]);
        while($order3){
            $order_no = $this->createCancelNo();
            $order3 = Order::findOne(['order_no'=>$order_no]);
        }
        $order->order_no = $order_no;
        $order->user_id = $user_id;
        $order->goods_amount = $goods_amount;
        if($channel_amount<88){
            $order->shipping_fee = 10;
        }else{
            $order->shipping_fee = 0;
        }
        $order->channel_amount = $channel_amount;
        $order_amount = $goods_amount+$order->shipping_fee;
        $order->order_amount = $order_amount;
        if($channel_code){
            $channel = Channel::find()->where(['channel_code'=>$channel_code])->asArray()->one();
            $order->channel_id = $channel['channel_id'];
        }
        $order_time = date('Y-m-d H:i:s');
        $order->order_time = $order_time;
        $order->consignee = $name;
        $order->consignee_phone = $phone;
        $order->consignee_province = $province;
        $order->consignee_city = $city;
        $order->consignee_district = $district;
        $order->consignee_address = $address;
        $result1 = $order->save();
        $result2 = true;
        $result3 = true;
        foreach($skus AS $key=>$value){
            $orderGoods = new OrderGoods();
            $orderGoods->order_id = $order->order_id;
            $orderGoods->yx_goods_id = $value['yx_goods_id'];
            $orderGoods->goods_id = $value['goods_id'];
            $orderGoods->goods_name = $value['goods_name'];
            $orderGoods->sku_id = $value['sku_id'];
            $orderGoods->yx_sku_id = $value['yx_sku_id'];
            $orderGoods->sku_pic = str_replace(Yii::$app->params['pic_domain'],"",$value['sku_pic']);
            $orderGoods->sku_spec = json_encode($value['sku_spec']);
            $orderGoods->channel_price = $value['channel_price'];
            $orderGoods->sku_price = $value['sku_price'];
            $orderGoods->buy_num = $value['num'];
            $result2 &= $orderGoods->save();
            $cart = Cart::findOne(['user_id'=>(int)$user_id,'sku_id'=>(int)$value['sku_id']]);
            if(!$is_buynow && $cart)
                $result3 &= $cart->delete();
        }
        if($result1 && $result2 && $result3){
            $orderLogic = new OrderLogic();
            $orderLogic->beanstalkProducer($order->order_id,1,3600);
            $transaction->commit();
            return true;
        }else{
            $transaction->rollBack();
            return false;
        }
    }

    private function createOrderNo(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


}
